#!/usr/bin/env python

"Run on Mobile"


import btsocket
import appuifw
import messaging
import re

import re

re_tags = re.compile("<([a-z_]+)>(.*?)</\\1>", re.I+re.U+re.S+re.M)

def xml2dict(sXML):
    "Regular expression based xml2dict"
    D = {}
    matches = re_tags.findall(sXML)
    
    for match in matches:
        k = match[0]
        
        if len(re_tags.findall(match[1]))<1:
            D[k] = match[1]
        else:
            D[k] = xml2dict(match[1])
        
    
    return D

def sendsms(number, message):
    print "sending message to: %s" % number,
    messaging.sms_send(number,message)
    print " .... DONE"

#def xml2dict(sXML):
#    "Convert XML to a dictionary object"
#    
#    try:
#        
#        D = {}
#        sXML = sXML.decode('utf-8')
#        sXML = sXML.encode('ascii', 'ignore')
#        #sXML = unicode(sXML, 'ascii')
#        
#        E = xml.etree.ElementTree.fromstring(sXML)
#        for tag in ['CMD', 'CONTACT', 'MESSAGE']:
#            
#            t = E.find(tag)
#            if None != t:
#                #if 'DURATIONS' == tag:
#                #    t = E.find('DURATIONS/FORSALE')
#                #    if None != t:
#                #        city_dict['durations'] = {'forsale': t.text}
#                #elif 'REGIONLIST' == tag:
#                #    regions = t.findall('REGION')
#                #    
#                #    regionlist = []
#                #    for region in regions:
#                #        rdict = {'regionname': none_to_empty(region.find('REGIONNAME').text).strip(), 'regionurl': none_to_empty(region.find('REGIONURL').text).strip()}
#                #        
#                #        if None != region.find('SUBREGIONLIST'):
#                #            subregions = []
#                #            
#                #            SRs = region.find('SUBREGIONLIST').findall('SUBREGION')
#                #            for subregion in SRs:
#                #                subregions.append({'subregionname': none_to_empty(subregion.find('SUBREGIONNAME').text).strip(),'subregionurl': none_to_empty(subregion.find('SUBREGIONURL').text).strip()})
#                #            
#                #            rdict['subregionlist'] = subregions
#                #        
#                #        regionlist.append(rdict)
#                #    
#                #    city_dict['regionlist'] = regionlist
#                #    
#                #else:
#                #    city_dict[tag.lower()] = t.text
#                D[tag.lower()] = t.text
#        
#        return D
#    
#    except (Exception), diag:
#        #print "ERROR: " + str(diag)
#        #print str(sXML)
#        return D

def open_srv_sock():
    SERVER_PORT = 21
    #server_sock = btsocket.socket(btsocket.AF_BT,btsocket.SOCK_STREAM)
    server_sock = btsocket.socket(btsocket.AF_BT, btsocket.SOCK_STREAM)
    server_sock.bind(("",SERVER_PORT))
    server_sock.listen(1)
    return server_sock
    
if '__main__' == __name__:
    
    
    #btsocket.bt_advertise_service(u'CellShellServer', server_sock, True, btsocket.RFCOMM)
    server_sock = open_srv_sock()
    while True:
        
        print "waiting for incoming connection"
        client_sock,address = server_sock.accept()
        print "Accepted connection from %s" % str(address)
    
        print "waiting for data"
        
        data = ''
        while True:
            try:
                data = client_sock.recv(2048)
                #print "Got Data: " + data
            except Exception, e:
                #print "Got Error: %s" % repr(e)
                #a = repr(e)
                break
            
            if len(data) == 0:
                break
            
            
        try:
            print "Data received is: %s" % data
            #client_sock.send("OK")
            if len(data)>0:
                cmd_info = xml2dict(data)
                
                print repr(cmd_info)
                print type(cmd_info)
                if 'cmdinfo' in cmd_info:
                    cmd_info = cmd_info['cmdinfo']
                    
                if type(cmd_info) == type( {} ):
                    if 'cmd' in cmd_info:
                        cmd = cmd_info['cmd']
                        print "Command is: " + cmd
                        
                        if 'SENDSMS' == cmd:
                            sendsms(cmd_info['contact'], cmd_info['message'])
            
        except Exception, e:
            print "Error occured: %s" % repr(e)
    
        client_sock.close()
        client_sock = None
        
    server_sock.close()
    server_sock = None
    print "connection closed"
    
    
    
    
